package com.graduate.controller;

import com.graduate.exception.CustomException;
import com.graduate.po.*;
import com.graduate.service.*;
import com.graduate.utils.Constant;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


/**
 * Created by lx on 2021/3/4.
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Resource(name = "userServiceImpl")
    private UserService userService;

    @Resource(name = "userloginServiceImpl")
    private UserloginService userloginService;

    @Resource(name = "roleServiceImpl")
    private  RoleService roleService;

    @Resource(name = "paymentServiceImpl")
    private PaymentService paymentService;

    /*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<首页操作>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
    @RequestMapping(value = "index")
    public String index(Model model, HttpServletRequest request) throws Exception {
        return "admin/index";
    }

    /*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<用户操作>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/

    //  用户信息显示
    @RequestMapping("/userList")
    public String userList(Model model, Integer page) throws Exception {
        List<User> list = null;
        //页码对象
        PagingVO pagingVO = new PagingVO();
        //设置总页数
        pagingVO.setTotalCount(userService.getUserCount());
        if (page == null || page == 0) {
            pagingVO.setToPageNo(1);
            list = userService.findByPaging(1);
        } else {
            pagingVO.setToPageNo(page);
            list = userService.findByPaging(page);
        }

        model.addAttribute("userList", list);
        model.addAttribute("pagingVO", pagingVO);

        return "admin/userList";

    }

    //  添加用户信息页面显示
    @RequestMapping(value = "/addUser", method = {RequestMethod.GET})
    public String addUserUI(Model model) throws Exception {
        // 查询角色列表
        List<Role> list = roleService.findAll();
        model.addAttribute("roleList", list);
        return "admin/addUser";
    }

     // 添加用户信息操作
    @RequestMapping(value = "/addUser", method = {RequestMethod.POST})
    public String addUser(User UserCustom, Model model, HttpServletRequest request) throws Exception {
        // 先判断参数是否合法1、当前用户是否已存在
        List<User> userList = userService.findByName(UserCustom.getUserName());
        if (!(userList == null || userList.size() == 0)) {
            model.addAttribute("message", "用户名重复");
            return "error";
        }

        Date now = new Date();
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        UserCustom.setCreatedBy(user.getUserName());
        UserCustom.setUpdatedBy(user.getUserName());
        UserCustom.setCreatedDate(now);
        UserCustom.setUpdatedDate(now);
        Boolean result = userService.save(UserCustom);

        //添加成功后，也添加到登录表
        Userlogin userlogin = new Userlogin();
        userlogin.setUserName(UserCustom.getUserName());
        userlogin.setPassword("123");
        userlogin.setRole(2);
        userloginService.save(userlogin);

        //重定向
        return "redirect:/admin/userList";
    }

    // 修改用户信息页面显示
    @RequestMapping(value = "/editUser", method = {RequestMethod.GET})
    public String editUserUI(Integer id, Model model) throws Exception {
        if (id == null) {
            //加入没有带用户id就进来的话就返回用户显示页面
            return "redirect:/admin/userList";
        }
        User UserCustom = userService.findById(id);
        if (UserCustom == null) {
            throw new CustomException("未找到该名用户");
        }
        // 查询角色列表
        List<Role> list = roleService.findAll();
        model.addAttribute("roleList", list);
        model.addAttribute("user", UserCustom);
        return "/admin/editUser";
    }

    // 修改用户信息处理
    @RequestMapping(value = "/editUser", method = {RequestMethod.POST})
    public String editUser(User UserCustom, HttpServletRequest request) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        UserCustom.setUpdatedBy(user.getUserName());
        Date now = new Date();
        UserCustom.setUpdatedDate(now);
        userService.updataById(UserCustom.getUserID(), UserCustom);

        //重定向
        return "redirect:/admin/userList";
    }

    // 查看用户信息
    @RequestMapping(value = "/viewUser", method = {RequestMethod.GET})
    public String viewUserUI(Integer id, Model model) throws Exception {
        if (id == null) {
            //加入没有带用户id就进来的话就返回用户显示页面
            return "redirect:/admin/userList";
        }
        User UserCustom = userService.findById(id);
        if (UserCustom == null) {
            throw new CustomException("未找到该名用户");
        }
        // 查询角色列表
        List<Role> list = roleService.findAll();
        Role currentRole = null;
        for(int i = 0; i < list.size(); i++) {
            Role item = list.get(i);
            if (item.getRole() == UserCustom.getRole()) {
                model.addAttribute("roleItem", item);
                break;
            }
        }
        model.addAttribute("user", UserCustom);
        return "/admin/viewUser";
    }

    // 删除用户
    @RequestMapping(value = "/removeUser", method = {RequestMethod.GET} )
    private String removeUser(Integer id) throws Exception {
        if (id == null) {
            //加入没有带用户id就进来的话就返回用户显示页面
            return "admin/userList";
        }
        userService.removeById(id);
        userloginService.removeByName(id.toString());

        return "redirect:/admin/userList";
    }

    // 搜索用户
    @RequestMapping(value = "searchUser", method = {RequestMethod.POST})
    private String searchUser(String findByName, Model model) throws Exception {

        List<User> list = userService.findByName(findByName);

        model.addAttribute("userList", list);
        return "admin/userList";
    }

    /*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<缴费操作>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/

    // 缴费管理
    @RequestMapping(value = "/feeList", method = {RequestMethod.GET})
    public String feeList(Model model, Integer page) throws Exception {
        List<PaymentCustom> list = null;
        //页码对象
        PagingVO pagingVO = new PagingVO();
        //设置总页数
        pagingVO.setTotalCount(paymentService.getUserCount());
        if (page == null || page == 0) {
            pagingVO.setToPageNo(1);
            list = paymentService.findByPaging(1);
        } else {
            pagingVO.setToPageNo(page);
            list = paymentService.findByPaging(page);
        }

        model.addAttribute("feeList", list);
        model.addAttribute("pagingVO", pagingVO);
        return "admin/feeList";
    }

    @RequestMapping(value = "/userFee", method = {RequestMethod.GET})
    public String userFeeUI(Integer id, Model model) throws Exception {
        if (id == null) {
            //加入没有带用户id就进来的话就返回用户显示页面
            return "redirect:/admin/userList";
        }
        User UserCustom = userService.findById(id);
        if (UserCustom == null) {
            throw new CustomException("未找到该名用户");
        }
        model.addAttribute("user", UserCustom);
        return "admin/userFee";
    }

    @RequestMapping(value = "/userFee", method = {RequestMethod.POST})
    public String userFee(Payment payment, Model model) throws  Exception {
        Boolean result = paymentService.save(payment);
        if (!result) {
            model.addAttribute("message", "新增出现异常");
            return "error";
        }
        paymentService.updateBalance(payment);
        //添加成功后，更新余额

        return "redirect:/admin/feeList";

    }

    @RequestMapping(value = "/userFeeList", method = {RequestMethod.GET})
    public String userFeeList(Model model,Integer id, Integer page) throws Exception {
        List<PaymentCustom> list = null;
        //页码对象
        PagingVO pagingVO = new PagingVO();
        //设置总页数
        pagingVO.setTotalCount(paymentService.getPaymentCountByUserID(id));
        if (page == null || page == 0) {
            pagingVO.setToPageNo(1);
            list = paymentService.findByPagingEachByID(id, 1);
        } else {
            pagingVO.setToPageNo(page);
            list = paymentService.findByPagingEachByID(id, page);
        }
        model.addAttribute("userFeeList", list);
        model.addAttribute("pagingVO", pagingVO);
        model.addAttribute("curUserID", id);
        return "admin/userFeeList";
    }

    //搜索缴费记录
    @RequestMapping(value = "searchUserFee", method = {RequestMethod.POST})
    private String searchUserFee(Model model, String userName) throws Exception {
        List<PaymentCustom> list = null;
        list = paymentService.findByPagingEach(userName);
        model.addAttribute("userFeeList", list);
        return "admin/userFeeList";
    }

    /*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<其他操作>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/

    // 普通用户账号密码重置
    @RequestMapping("/userPasswordRest")
    public String userPasswordRestUI() throws Exception {
        return "admin/userPasswordRest";
    }

    // 普通用户账号密码重置处理
    @RequestMapping(value = "/userPasswordRest", method = {RequestMethod.POST})
    public String userPasswordRest(Userlogin userlogin) throws Exception {

        Userlogin u = userloginService.findByName(userlogin.getUserName());

        if (u != null) {
            if (u.getRole() == 0) {
                throw new CustomException("该账户为管理员账户，没法修改");
            }
            u.setPassword(userlogin.getPassword());
            userloginService.updateByName(userlogin.getUserName(), u);
        } else {
            throw new CustomException("没找到该用户");
        }

        return "admin/userPasswordRest";
    }

    // 本账户密码重置
    @RequestMapping("/passwordRest")
    public String passwordRestUI() throws Exception {
        return "admin/passwordRest";
    }
}
